/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.tool;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.logos.tool.log.LogUtil;

/**
 * @author Young Ken
 */

public class ApplicationUtil {

    private static final String TAG = "ApplicationUtil";

    //https://github.com/guolindev/booksource/issues/5
    @SuppressLint("StaticFieldLeak")
    private static final Application INSTANCE;
    public static final int ENV_RELEASE = 0;
    public static final int ENV_BETA = 1;
    public static final int ENV_ALPHA = 2;

    static {
        Application app = null;
        try {
            app = (Application) Class.forName("android.app.AppGlobals")
                    .getMethod("getInitialApplication").invoke(null);
            if (app == null) {
                throw new IllegalStateException(
                        "Static initialization of Applications must be on main thread.");
            }
        } catch (final Exception e) {
            Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
            try {
                app = (Application) Class.forName("android.app.ActivityThread")
                        .getMethod("currentApplication").invoke(null);
            } catch (final Exception ex) {
                LogUtil.error(TAG, "Failed to get current application from ActivityThread."
                        + LogUtil.getStackTrace(e));
            }
        } finally {
            INSTANCE = app;
        }
    }

    public static Context getContext() {
        return INSTANCE.getApplicationContext();
    }
}
